#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>

void printAllProcesses() {
    DIR *dir;
    struct dirent *entry;

    dir = opendir("/proc");
    if (dir == NULL) {
        perror("opendir()");
        exit(EXIT_FAILURE);
    }

    printf("%-10s %s\n", "PID", "Name");
    printf("-----------------------\n");

    while ((entry = readdir(dir)) != NULL) {
        if (entry->d_type == DT_DIR) {
            char path[128];
            FILE *fp;
            char name[256];

            snprintf(path, sizeof(path), "/proc/%s/cmdline", entry->d_name);
            fp = fopen(path, "r");
            if (fp != NULL) {
                if (fgets(name, sizeof(name), fp) != NULL) {
                    int len = strlen(name);
                    if (len > 0 && name[len - 1] == '\n') {
                        name[len - 1] = '\0';  // 去掉换行符
                    }
                    printf("%-10s %s\n", entry->d_name, name);
                }
                fclose(fp);
            }
        }
    }

    closedir(dir);
}

void killProcess(int pid) {
    if (kill(pid, SIGKILL) == 0) {
        printf("Process with PID %d has been killed.\n", pid);
    } else {
        perror("kill()");
        exit(EXIT_FAILURE);
    }
}

int main(int argc, char *argv[]) {
    if (argc == 1) {
        // 打印所有进程
        printAllProcesses();
    } else if (argc == 2) {
        // 杀死指定进程
        int pid = atoi(argv[1]);
        killProcess(pid);
    } else {
        printf("Usage: %s [PID]\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    return 0;
}

